package info.batcloud.fanli.admin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jd.open.api.sdk.JdException;
import info.batcloud.fanli.admin.permission.ManagerPermissions;
import info.batcloud.fanli.admin.permission.annotation.Permission;
import info.batcloud.fanli.core.constants.JosConstatns;
import info.batcloud.fanli.core.jos.JosApp;
import info.batcloud.fanli.core.service.JdUnionApiService;
import info.batcloud.fanli.core.service.SystemSettingService;
import info.batcloud.fanli.core.settings.JdAuthSetting;
import info.batcloud.laxiaoke.open.domain.jd.union.GoodsCategory;
import info.batcloud.laxiaoke.open.request.jd.union.GoodsCategoryQueryRequest;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.inject.Inject;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/api/jos")
public class JosController {

    @Inject
    @Qualifier(JosConstatns.UNION_APP)
    private JosApp unionApp;

    @Inject
    private SystemSettingService systemSettingService;

    @Inject
    private JdUnionApiService jdUnionApiService;

    @GetMapping("/auth")
    @Permission(ManagerPermissions.JD_AUTH_SETTING)
    public String auth() throws UnsupportedEncodingException {

        String redirectUrl = "https://oauth.jd.com/oauth/authorize?response_type=code&client_id=%s&" +
                "redirect_uri=%s&state=%s";
        redirectUrl = String.format(redirectUrl, new String[]{unionApp.getAppKey(), URLEncoder.encode(unionApp.getRedirectUrl(), "utf8"), "auth"});

        return "redirect:" + redirectUrl;
    }

    @GetMapping("/callback")
    public String callback(String code, String state) throws IOException, JdException {

        String url = "https://oauth.jd.com/oauth/token?grant_type=authorization_code&client_id=" + unionApp.getAppKey()

                + "&client_secret=" + unionApp.getAppSecret()

                + "&scope=read&redirect_uri=" + unionApp.getRedirectUrl()

                + "&code=" + code

                + "&state=" + state;

        URL uri = new URL(url);

        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();

        conn.setRequestMethod("POST");

        int responseCode = conn.getResponseCode();

        InputStream is = conn.getInputStream();

        String jsonStr = IOUtils.toString(is, "gbk");

        JSONObject jsonObject = JSON.parseObject(jsonStr);
        JdAuthSetting jdAuthSetting = systemSettingService.findActiveSetting(JdAuthSetting.class);

        jdAuthSetting.setAccessToken(jsonObject.getString("access_token"));
        jdAuthSetting.setCode(jsonObject.getString("code"));
        jdAuthSetting.setExpiresIn(new Date(System.currentTimeMillis() + jsonObject.getLong("expires_in") * 1000));
        jdAuthSetting.setRefreshToken(jsonObject.getString("refresh_token"));
        jdAuthSetting.setScope(jsonObject.getString("scope"));
        jdAuthSetting.setTime(new Date(jsonObject.getLong("time")));
        jdAuthSetting.setTokenType(jsonObject.getString("token_type"));
        jdAuthSetting.setUid(jsonObject.getString("uid"));
        jdAuthSetting.setUserNick(jsonObject.getString("user_nick"));
        systemSettingService.saveSetting(jdAuthSetting, 0);
        systemSettingService.activeSetting(JdAuthSetting.class, 0);
        return "redirect:/auto-close.html";

    }

    @GetMapping("/goodsCategory/list/{parentId}-{grade}")
    @ResponseBody
    public Object listItemCat(@PathVariable int parentId, @PathVariable int grade) throws JdException {
        GoodsCategoryQueryRequest request = new GoodsCategoryQueryRequest();
        request.setParentId(parentId);
        request.setGrade(grade);
        List<GoodsCategory> list = jdUnionApiService.queryGoodsCategory(request).getData().getData();
        return list == null ? Collections.EMPTY_LIST : list;
    }

}
